package com.shallowUniverse.dmp.netty.handler;

import com.shallowUniverse.dmp.service.TransferService;
import com.shallowUniverse.dmp.utils.SpringBeanUtils;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @author Shuai Guo
 * @version 1.0
 * @description
 * @date 2021/8/5
 */
public class HttpChannelHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, FullHttpRequest request) throws Exception {
        //定义transferId
        long transferId = 0;
        //从请求对象中获取转换id
        QueryStringDecoder decoder = new QueryStringDecoder(request.uri());
        //拿到转换id
        List<String> params = decoder.parameters().get("transferId");
        //判断是否为空
        if (CollectionUtils.isEmpty(params)) {
            //从请求内容中获取
            String json = request.content().toString(CharsetUtil.UTF_8);
            //判断是否为空
            if (ObjectUtils.isEmpty(json)) {
                //从uri获取
                String[] uriArray = request.uri().split("/");
                //判断是否为空
                if (ObjectUtils.isEmpty(uriArray) || uriArray.length == 0) {
                    writeError(channelHandlerContext, "请传递转换sid");
                    return;
                }
                String lastParam = uriArray[uriArray.length - 1];
                //判断是否为空或者不是数字
                String regx = "^[1-9]+$";
                if (!ObjectUtils.isEmpty(lastParam) || !lastParam.matches(regx)) {
                    transferId = Long.parseLong(lastParam);
                } else {
                    writeError(channelHandlerContext, "请传递转换sid");
                    return;
                }
            }
        } else {
            transferId = Long.parseLong(params.get(0));
        }

        //从Spring容器获取转换服务对象
        TransferService transferService = SpringBeanUtils.getBean(TransferService.class);
        //开始转换
        transferService.transfer(transferId);

        writeError(channelHandlerContext, "数据转换中......");
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channelReadComplete");
        super.channelReadComplete(ctx);
        ctx.flush(); // 4
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("exceptionCaught");
        if (null != cause) {
            cause.printStackTrace();
        }
        if (null != ctx) {
            ctx.close();
        }
    }

    private void writeError(ChannelHandlerContext channelHandlerContext, String msg) {
        DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                HttpResponseStatus.OK,
                Unpooled.wrappedBuffer(msg.getBytes()));

        HttpHeaders heads = response.headers();
        heads.add(HttpHeaderNames.CONTENT_TYPE, "application/json;charset=UTF-8");
        heads.add(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
        heads.add(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);

        channelHandlerContext.write(response);
    }
}
